#!/usr/bin/env python3
"""
Progressive Indentation Analysis for GSI Technical Report
Analyzes LaTeX document structure for systematic indentation issues
"""

import os
import re
import sys
from pathlib import Path

def analyze_indentation_patterns():
    """Analyze indentation patterns across the document"""
    
    # Define the LaTeX directory
    latex_dir = Path(".")
    
    # Patterns to look for
    patterns = {
        'itemize': r'\\begin\{itemize\}',
        'enumerate': r'\\begin\{enumerate\}',
        'quote': r'\\begin\{quote\}',
        'quotation': r'\\begin\{quotation\}',
        'custom_env': r'\\begin\{[^}]*\}',
        'leftskip': r'\\leftskip',
        'rightskip': r'\\rightskip',
        'parindent': r'\\parindent',
        'addtolength': r'\\addtolength',
        'setlength': r'\\setlength'
    }
    
    # Track environment nesting by file
    env_stack = []
    file_analysis = {}
    
    # Get all .tex files in order
    tex_files = sorted(latex_dir.glob("part*/ch*.tex"))
    
    print("=== PROGRESSIVE INDENTATION ANALYSIS ===\n")
    
    for tex_file in tex_files:
        print(f"Analyzing: {tex_file}")
        
        with open(tex_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # Track line-by-line analysis
        lines = content.split('\n')
        
        # Count environments
        env_counts = {
            'itemize': len(re.findall(r'\\begin\{itemize\}', content)),
            'enumerate': len(re.findall(r'\\begin\{enumerate\}', content)),
            'quote': len(re.findall(r'\\begin\{quote\}', content)),
            'quotation': len(re.findall(r'\\begin\{quotation\}', content)),
            'equation': len(re.findall(r'\\begin\{equation\}', content)),
            'lstlisting': len(re.findall(r'\\begin\{lstlisting\}', content)),
            'table': len(re.findall(r'\\begin\{table\}', content)),
            'tabular': len(re.findall(r'\\begin\{tabular\}', content))
        }
        
        # Check for indentation commands
        indent_commands = {
            'leftskip': len(re.findall(r'\\leftskip', content)),
            'rightskip': len(re.findall(r'\\rightskip', content)),
            'parindent': len(re.findall(r'\\parindent', content)),
            'addtolength': len(re.findall(r'\\addtolength', content)),
            'setlength': len(re.findall(r'\\setlength', content))
        }
        
        # Track actual whitespace patterns
        leading_spaces = []
        for line_num, line in enumerate(lines, 1):
            stripped = line.lstrip()
            if stripped and not stripped.startswith('%'):  # Skip empty and comment lines
                spaces = len(line) - len(stripped)
                if spaces > 0:
                    leading_spaces.append((line_num, spaces))
        
        file_analysis[str(tex_file)] = {
            'environments': env_counts,
            'indent_commands': indent_commands,
            'leading_spaces': leading_spaces
        }
        
        # Print summary for this file
        print(f"  Environments: {env_counts}")
        print(f"  Indent commands: {indent_commands}")
        if leading_spaces:
            print(f"  Leading spaces found: {len(leading_spaces)} instances")
            max_spaces = max(spaces for _, spaces in leading_spaces)
            print(f"  Max indentation: {max_spaces} spaces")
        print()
    
    # Analyze progression across files
    print("=== PROGRESSION ANALYSIS ===")
    max_spaces_by_file = []
    for filename, analysis in file_analysis.items():
        leading_spaces = analysis['leading_spaces']
        if leading_spaces:
            max_spaces = max(spaces for _, spaces in leading_spaces)
            max_spaces_by_file.append((filename, max_spaces))
        else:
            max_spaces_by_file.append((filename, 0))
    
    # Sort by part number to track progression
    def extract_numbers(filename):
        try:
            part = int(re.search(r'part(\d+)', filename).group(1))
            chapter = int(re.search(r'ch(\d+)', filename).group(1))
            return (part, chapter)
        except:
            return (99, 99)  # Put files that don't match pattern at end
    
    max_spaces_by_file.sort(key=lambda x: extract_numbers(x[0]))
    
    print("Progression of maximum indentation:")
    for filename, max_spaces in max_spaces_by_file:
        print(f"  {os.path.basename(filename)}: {max_spaces} spaces")
    
    # Check for systematic increase
    spaces_values = [spaces for _, spaces in max_spaces_by_file]
    if spaces_values:
        print(f"\nIndentation trend:")
        print(f"  Early files (parts 1-3): avg {sum(spaces_values[:9])/len(spaces_values[:9]):.1f} spaces")
        print(f"  Late files (parts 10-11): avg {sum(spaces_values[-8:])/len(spaces_values[-8:]):.1f} spaces")
        
        # Check for systematic increase
        early_avg = sum(spaces_values[:9]) / len(spaces_values[:9])
        late_avg = sum(spaces_values[-8:]) / len(spaces_values[-8:])
        
        if late_avg > early_avg + 2:
            print(f"  ⚠️  DETECTED PROGRESSIVE INDENTATION: {late_avg - early_avg:.1f} space increase")
        else:
            print(f"  ✅ No significant progressive indentation detected")
    
    return file_analysis

def check_list_environment_nesting():
    """Check for deep nesting in list environments"""
    
    print("\n=== LIST ENVIRONMENT NESTING ANALYSIS ===")
    
    tex_files = sorted(Path(".").glob("part*/ch*.tex"))
    
    for tex_file in tex_files:
        with open(tex_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # Track nesting depth
        lines = content.split('\n')
        max_nesting = 0
        current_nesting = 0
        
        for line in lines:
            line = line.strip()
            if line.startswith('\\begin{itemize}') or line.startswith('\\begin{enumerate}'):
                current_nesting += 1
                max_nesting = max(max_nesting, current_nesting)
            elif line.startswith('\\end{itemize}') or line.startswith('\\end{enumerate}'):
                current_nesting -= 1
        
        if max_nesting > 2:
            print(f"  {tex_file.name}: Max nesting depth = {max_nesting}")

if __name__ == "__main__":
    analysis = analyze_indentation_patterns()
    check_list_environment_nesting()